﻿using BW.Mes.WinForms.BasicData;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static BW.Mes.WinForms.BasicData.MaterialForm;

namespace BW.Mes.WinForms.BasicData
{
    public partial class MaterialForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _materialApiBaseUrl = "https://localhost:7274";
        private bool _showDeletedMaterials = false; // 控制是否显示已删除的物料

        public MaterialForm()
        {
            InitializeComponent();
            //初始化httpClient
            _httpClient = new HttpClient();
            _httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

            // 物料类型下拉框初始化
            comboBoxEditType.Properties.Items.Clear();
            comboBoxEditType.Properties.Items.AddRange(new string[] { "原材料", "半成品", "成品", "其他" });
            comboBoxEditType.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;

            // 窗体加载时获取数据
            this.Load += MaterialForm_Load;
            
            // 设置网格的操作列
            SetupGridActionColumn();

            gridView1.CustomUnboundColumnData += gridView1_CustomUnboundColumnData;
        }

        private void SetupGridActionColumn()
        {
            // 创建操作列
            var actionColumn = new DevExpress.XtraGrid.Columns.GridColumn();
            actionColumn.Caption = "操作";
            actionColumn.Name = "ActionColumn";
            actionColumn.Visible = true;
            actionColumn.VisibleIndex = 9;
            actionColumn.Width = 240;
            actionColumn.MinWidth = 240;
            
            // 设置操作列的显示模板
            actionColumn.ColumnEdit = new DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit();
            var buttonEdit = actionColumn.ColumnEdit as DevExpress.XtraEditors.Repository.RepositoryItemButtonEdit;
            buttonEdit.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
            buttonEdit.Buttons.Clear();
            
            // 添加修改按钮
            var editButton = new DevExpress.XtraEditors.Controls.EditorButton();
            editButton.Caption = "修改";
            editButton.Width = 60;
            buttonEdit.Buttons.Add(editButton);
            
            // 添加删除按钮
            var deleteButton = new DevExpress.XtraEditors.Controls.EditorButton();
            deleteButton.Caption = "删除";
            deleteButton.Width = 60;
            buttonEdit.Buttons.Add(deleteButton);
            
            // 添加恢复按钮
            var restoreButton = new DevExpress.XtraEditors.Controls.EditorButton();
            restoreButton.Caption = "恢复";
            restoreButton.Width = 60;
            buttonEdit.Buttons.Add(restoreButton);
            
            // 绑定按钮点击事件
            buttonEdit.ButtonClick += ButtonEdit_ButtonClick;
            
            // 添加操作列到网格
            gridView1.Columns.Add(actionColumn);
        }

        private void ButtonEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            // 获取当前行数据
            var rowHandle = gridView1.FocusedRowHandle;
            if (rowHandle >= 0)
            {
                var material = gridView1.GetRow(rowHandle) as MaterialModel;
               
            }
        }

        private async void MaterialForm_Load(object sender, EventArgs e)
        {
            await LoadWorkshopData();
        }
        // 加载仓库数据
        private async Task LoadWorkshopData()
        {
            try
            {
                var material = await GetApiDataAsync<List<MaterialModel>>("api/Material/GetMaterial");
                gridControl1.DataSource = null;
                gridControl1.DataSource = material;

                gridView1.PopulateColumns();
                gridView1.BestFitColumns();
                gridView1.RefreshData();

                

                // 设置多选和复选框在最前面
                gridView1.OptionsSelection.MultiSelect = true;
                gridView1.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;
                gridView1.Columns[0].VisibleIndex = 0;

                EnsureSerialNumberColumn();
                AfterBindMaterialData();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败: {ex.Message}\n{ex.StackTrace}", "错误");
            }
        }
        private async Task<T> GetApiDataAsync<T>(string endpoint)
        {
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync($"{_materialApiBaseUrl}/{endpoint}");
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();

                // 调试显示原始响应内容
                Console.WriteLine($"API响应: {responseBody}");

                // 先解析为JObject以便提取内部数据
                var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);

                // 假设数组数据在"data"字段中
                if (jsonObject["pageDatas"] != null)
                {
                    string dataJson = jsonObject["pageDatas"].ToString();
                    Console.WriteLine($"提取的pageDatas字段: {dataJson}");

                    return JsonConvert.DeserializeObject<T>(dataJson);
                }

                return JsonConvert.DeserializeObject<T>(responseBody);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取数据失败: {ex.Message}\n{ex.StackTrace}", "错误");
                return default;
            }
        }
        // 提交数据到API
        public async Task<bool> PostApiDataAsync<T>(string endpoint, T data)
        {
            try
            {
                string jsonData = JsonConvert.SerializeObject(data);
                HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                HttpResponseMessage response = await _httpClient.PostAsync($"{_materialApiBaseUrl}/{endpoint}", content);
                response.EnsureSuccessStatusCode();
                return true;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"提交数据失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        public class MaterialModel
        {
            public long Id { get; set; }
            /// <summary>
            /// 物料编号
            /// </summary>
            [DisplayName("物料编号")]
            public string MaterialCode { get; set; }
            /// <summary>
            /// 物料名称
            /// </summary>
            [DisplayName("物料名称")]
            public string MaterialName { get; set; }
            /// <summary>
            /// 物料类型
            /// </summary>
            [DisplayName("物料类型")]
            public string MaterialType { get; set; }
            /// <summary>
            /// 工艺路线
            /// </summary>
            [DisplayName("工艺路线")]
            public string Routing { get; set; }
            /// <summary>
            /// 物料描述
            /// </summary>
            [DisplayName("物料描述")]
            public string MaterialMsg { get; set; }
            [DisplayName("创建人")]
            public string CreatedBy { get; set; }
            [DisplayName("创建时间")]
            public DateTime CreatedAt { get; set; } = DateTime.Now;
            [DisplayName("更新时间")]
            public DateTime? UpdatedAt { get; set; }
            
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            LoadWorkshopData();
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }

        private async Task LoadMaterialData()
        {
            try
            {
                // Reverted the API endpoint to the singular form based on the 404 error
                var material = await GetApiDataAsync<List<MaterialModel>>("api/Material/GetMaterial");

                // 确保清除旧数据源并重新设置
                gridControl1.DataSource = null;
                gridControl1.DataSource = material;

                // 确保网格视图显示数据
                gridView1.PopulateColumns();
                gridView1.BestFitColumns();
                gridView1.RefreshData();

                EnsureSerialNumberColumn();
                AfterBindMaterialData();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败: {ex.Message}\n{ex.StackTrace}", "错误");
            }
        }

        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            var form = new AddMaterialGroupForm();
            if (form.ShowDialog() == DialogResult.OK)
            {
                // 确保异步调用被正确等待
                await LoadMaterialData();
            }
        }

        private async void DeleteMaterial(long materialId)
        {
            try
            {
                // 软删除：更新IsDeleted和DeletedAt字段
                var softDeleteModel = new
                {
                    Id = materialId,
                    IsDeleted = true,
                    DeletedAt = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")
                };

                string jsonData = JsonConvert.SerializeObject(softDeleteModel);
                HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                
                // 使用PUT请求进行软删除
                var response = await _httpClient.PutAsync($"{_materialApiBaseUrl}/api/Material/SoftDeleteMaterial", content);
                
                if (response.IsSuccessStatusCode)
                {
                    XtraMessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    await LoadWorkshopData(); // 刷新数据
                }
                else
                {
                    string errorContent = await response.Content.ReadAsStringAsync();
                    XtraMessageBox.Show($"删除失败：{response.ReasonPhrase} - {errorContent}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"删除失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void RestoreMaterial(long materialId)
        {
            try
            {
                // 恢复：更新IsDeleted和DeletedAt字段
                var restoreModel = new
                {
                    Id = materialId,
                    IsDeleted = false,
                    DeletedAt = (string)null
                };

                string jsonData = JsonConvert.SerializeObject(restoreModel);
                HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
                
                // 使用PUT请求进行恢复
                var response = await _httpClient.PutAsync($"{_materialApiBaseUrl}/api/Material/RestoreMaterial", content);
                
                if (response.IsSuccessStatusCode)
                {
                    XtraMessageBox.Show("恢复成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    await LoadWorkshopData(); // 刷新数据
                }
                else
                {
                    string errorContent = await response.Content.ReadAsStringAsync();
                    XtraMessageBox.Show($"恢复失败：{response.ReasonPhrase} - {errorContent}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"恢复失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void simpleButtonModify_Click(object sender, EventArgs e)
        {
            var rowHandle = gridView1.FocusedRowHandle;
            if (rowHandle < 0)
            {
                XtraMessageBox.Show("请先选择要修改的物料！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var material = gridView1.GetRow(rowHandle) as MaterialModel;
            if (material == null)
            {
                XtraMessageBox.Show("未获取到物料信息！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            
            var updateForm = new UpdateMaterialForm(material);
            if (updateForm.ShowDialog() == DialogResult.OK)
            {
                await LoadWorkshopData();
            }
        }

        private async void simpleButtonDelete_Click(object sender, EventArgs e)
        {
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length == 0)
            {
                XtraMessageBox.Show("请先选择要删除的物料！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var confirm = XtraMessageBox.Show($"确定要删除选中的{selectedRows.Length}个物料吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (confirm != DialogResult.Yes) return;

            foreach (var rowHandle in selectedRows)
            {
                var material = gridView1.GetRow(rowHandle) as MaterialModel;
                if (material != null)
                {
                    await SoftDeleteMaterial(material.Id);
                }
            }
            await LoadWorkshopData();
        }

        private async Task SoftDeleteMaterial(long materialId)
        {
            try
            {
                var request = new HttpRequestMessage(HttpMethod.Put, $"{_materialApiBaseUrl}/api/Material/DeleteMaterial?id={materialId}");
                request.Content = new StringContent("{}", Encoding.UTF8, "application/json"); // 若后端不需要body可去掉
                var response = await _httpClient.SendAsync(request);
                if (!response.IsSuccessStatusCode)
                {
                    string errorContent = await response.Content.ReadAsStringAsync();
                    XtraMessageBox.Show($"删除失败：{response.ReasonPhrase} - {errorContent}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"删除失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadWorkshopData();
        }

        private void EnsureSerialNumberColumn()
        {
            if (gridView1.Columns["序号"] == null)
            {
                var col = gridView1.Columns.AddField("序号");
                col.Caption = "序号";
                col.UnboundType = DevExpress.Data.UnboundColumnType.Integer;
                col.Visible = true;
                col.VisibleIndex = 0;
            }
            else
            {
                gridView1.Columns["序号"].Visible = true;
                gridView1.Columns["序号"].VisibleIndex = 0;
            }
        }

        private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.Column.FieldName == "序号" && e.IsGetData)
            {
                e.Value = e.ListSourceRowIndex + 1;
            }
        }

        private void AfterBindMaterialData()
        {
            EnsureSerialNumberColumn();
            // 自动隐藏所有可能的Id列
            string[] idNames = { "Id", "ID", "id", "MaterialId", "MaterialID", "materialId" };
            foreach (var name in idNames)
            {
                var idColumn = gridView1.Columns[name];
                if (idColumn != null) idColumn.Visible = false;
            }
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            string code = textEditCode.Text.Trim();
            string name = textEditName.Text.Trim();
            string type = comboBoxEditType.Text.Trim();
            if (string.IsNullOrEmpty(code) && string.IsNullOrEmpty(name) && string.IsNullOrEmpty(type))
            {
                // 重新加载全部数据
                LoadMaterialData();
                return;
            }
            var data = gridControl1.DataSource as IEnumerable<object>;
            if (data == null) return;
            var filtered = data.Where(item =>
            {
                var t = item.GetType();
                var codeProp = t.GetProperty("MaterialCode") ?? t.GetProperty("编号");
                var nameProp = t.GetProperty("MaterialName") ?? t.GetProperty("名称");
                var typeProp = t.GetProperty("MaterialType") ?? t.GetProperty("类型");
                string codeVal = codeProp?.GetValue(item)?.ToString() ?? "";
                string nameVal = nameProp?.GetValue(item)?.ToString() ?? "";
                string typeVal = typeProp?.GetValue(item)?.ToString() ?? "";
                return (string.IsNullOrEmpty(code) || codeVal.Contains(code)) &&
                       (string.IsNullOrEmpty(name) || nameVal.Contains(name)) &&
                       (string.IsNullOrEmpty(type) || typeVal == type);
            }).ToList();
            gridControl1.DataSource = filtered;
            EnsureSerialNumberColumn();
            // 隐藏Id列
            string[] idNames = { "Id", "ID", "id", "MaterialId", "MaterialID", "materialId" };
            foreach (var nameId in idNames)
            {
                var idColumn = gridView1.Columns[nameId];
                if (idColumn != null) idColumn.Visible = false;
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            // 这里可以调用已有的删除逻辑或弹窗确认
            // 示例：
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length == 0)
            {
                XtraMessageBox.Show("请先选择要删除的物料！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var confirm = XtraMessageBox.Show($"确定要删除选中的{selectedRows.Length}个物料吗？", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (confirm != DialogResult.Yes) return;
            foreach (var rowHandle in selectedRows)
            {
                var material = gridView1.GetRow(rowHandle) as MaterialModel;
                if (material != null)
                {
                    // 调用已有的软删除方法
                    _ = SoftDeleteMaterial(material.Id);
                }
            }
            LoadMaterialData();
        }

        private void btnModify_Click(object sender, EventArgs e)
        {
            var selectedRows = gridView1.GetSelectedRows();
            if (selectedRows.Length != 1)
            {
                XtraMessageBox.Show("请只选择一条要修改的物料！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var material = gridView1.GetRow(selectedRows[0]) as MaterialModel;
            if (material == null)
            {
                XtraMessageBox.Show("未获取到物料信息！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
         
            var updateForm = new UpdateMaterialForm(material);
            if (updateForm.ShowDialog() == DialogResult.OK)
            {
                LoadMaterialData();
            }
        }
    }
}